package com.lmb.todo.utils;

import com.lmb.todo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lmb
 */
@Component
public class AuthUtil {

    @Autowired
    private HttpServletRequest httpServletRequest;

    /**
     * 用户登录成功，认证用户，往 session 中写入用户信息并返回生成的 token 字符串
     * @param user User
     * @return String
     */
    public String auth(User user) {
        String token = JwtUtil.createToken(user);
        Map<String, Object> userInfo = JwtUtil.getPayload(token);
        HttpSession session = httpServletRequest.getSession();
        session.setAttribute("userInfo", userInfo);
        session.setAttribute("token", token);
        return token;
    }

    /**
     * 用户退出登录，清空 session 中的信息并销毁 token
     */
    public void unAuth() {

    }

    /**
     * 获取当前登录的用户信息
     * @return Map<String, Object>
     */
    public HashMap getAuthUserInfo() {
        HttpSession session = httpServletRequest.getSession();
        return (HashMap) session.getAttribute("userInfo");
    }

}
